package com.y.fund.utils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;

/** 封装了XML转换成object，object转换成XML的代码 */
public class XmlUtil {
	
	static final String charset="UTF-8";

    /**
     * 将对象直接转换成String类型的 XML输出
     *
     * @param obj
     * @return
     */
    public static String toXml(Object obj) {
        // 创建输出流
        StringWriter sw = new StringWriter();
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            // 将对象转换成输出流形式的xml
            marshaller.marshal(obj, sw);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    /**
     *  将String类型的xml转换成对象
     *
     * @param clazz
     * @param xmlStr
     * @return
     */
    public static <T>T toObj(Class<T> clazz, String xmlStr) {
        T xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = (T)unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

    /**
     * 将xml转为document
     *
     * @param xmlStr xml的string
     * @return
     */
    public static Document str2Document(String xmlStr) {
        Document doc = null;
        StringReader sr = new StringReader(xmlStr);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfiguration错误" + e);
        } catch (SAXException e) {
            System.out.println("SAX错误" + e);
        } catch (IOException e) {
            System.out.println("IO错误" + e);
        }
        return doc;
    }

    /**
     * 将document生成xml文件
     *
     * @param fileName
     * @param document
     */
    public synchronized static void createXml(String fileName, Document document) {
        System.out.println("============进入生成xml方法：" + new Date().toLocaleString() + "=================");
        try {
            // 判断文件是否存在，如存在就删掉它
            File file = new File(fileName);
            if (file.exists()) {
                file.delete();
                System.out.println("==============删除xml文件==============");
            }
            /** 将document中的内容写入文件中 */
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new FileOutputStream(fileName));
            transformer.transform(source, result);
            System.out.println("--------------------------------" + "更新 XML文件成功" + "-------------------------------------");
        } catch (final Exception exception) {
            System.out.println("更新" + fileName + "出错：" + exception);
        }
        System.out.println("============退出生成xml方法：" + new Date().toLocaleString() + "=================");
    }


}